package com.lemon.business.dao;

import com.lemon.constant.Constant;
import com.lemon.utils.DBUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author liuli
 * @Date 2020/10/13 21:05
 */
public class ConfigDao {
    private static final Logger LOG = LoggerFactory.getLogger(ConfigDao.class);

    private static final int TIME_OUT = 10;

    private static final String SELECT_MACHINE_SQL = "SELECT m.account AS account, m.upload_token as uploadToken, " +
            "m.os_name AS osNAme, m.pc_name AS pcName, m.memory_total AS memoryTotal FROM apm.machine AS m WHERE m.update_time > ?";

    public static Map<String, Map<String, String>> selectMachine(long lastUpdateTime){
        Map<String, Map<String, String>> result = new HashMap<>();
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtil.getConnection();
            statement = connection.prepareStatement(SELECT_MACHINE_SQL);
            statement.setTimestamp(1, new Timestamp(lastUpdateTime));
            statement.setQueryTimeout(TIME_OUT);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                Map<String, String> dataMap = result.computeIfAbsent(resultSet.getString("uploadToken"), k -> new HashMap<>());
                dataMap.put(Constant.TOKEN_REDIS_KEY, resultSet.getString("account"));
                if (StringUtils.isEmpty(resultSet.getString("osNAme")) || StringUtils.isEmpty(resultSet.getString("memoryTotal"))
                        || StringUtils.isEmpty(resultSet.getString("pcName"))) {
                    dataMap.put(Constant.ISUPDATE_REDIS_KEY, "1");
                } else {
                    dataMap.put(Constant.ISUPDATE_REDIS_KEY, "0");
                }
            }
            LOG.info("Machine data count:{}", result.size());
        } catch (Exception e) {
            LOG.error("selectMachine error", e);
        } finally {
            DBUtil.close(resultSet, statement, connection);
        }
        return result;
    }

}
